package com.cn.core.result;


import com.cn.core.utils.ListUtils;
import lombok.Getter;

import java.util.List;

/**
 * @Author SHANGGUAN
 **/
@Getter
public class Page<T> {

    private Integer pageNum;

    private Integer pageSize;

    private Integer total;

    private Integer totalPage;

    /**
     * 每页数据
     */
    private List<T> data;

    /**
     * 列表
     */
    private final List<T> list;

    public Page(Integer pageNum, Integer pageSize, Integer total, List<T> list) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.total = total;
        this.list = list;
    }

    public Page(Integer pageNum, Integer pageSize, List<T> list) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.list = list;
        if (ListUtils.isNotEmpty(list)) {
            total = list.size();
            // 计算总页数
            totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            // 起始位置
            int start = pageNum <= 0 ? 0 : (pageNum > totalPage ? (totalPage - 1) * pageSize : (pageNum - 1) * pageSize);
            // 终止位置
            int end = pageNum <= 0 ? (Math.min(pageSize, total)) : (Math.min(pageSize * pageNum, total));
            data = list.subList(start, end);
        }
    }


    public List<T> getData(Integer pageNum, Integer pageSize) {
        return ListUtils.subList(list, pageSize, pageNum);
    }


}
